package com.younion.business.impl;

import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javapns.back.PushNotificationManager;
import javapns.back.SSLConnectionHelper;
import javapns.data.Device;
import javapns.data.PayLoad;

import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;

import com.younion.business.IMessageService;
import com.younion.common.constants.MsgStatus;
import com.younion.common.paginator.Paginator;
import com.younion.dao.CustomerDAO;
import com.younion.dao.MessageDAO;
import com.younion.util.config.ConfigHelper;
import com.younion.vo.MessageVO;

import cpcns.component.common.base.BaseException;
import cpcns.jhsks.util.MapCollectionUtils;

 
public class MessageServiceImpl implements IMessageService {

	protected static final Log logger = LogFactory.getLog(MessageServiceImpl.class);

	private MessageDAO messageDAO;
	@Autowired
	private CustomerDAO customerDAO;
	//private CustomerAccountDAO customerAccountDAO;
	
	public Collection getAll() throws Exception {
		return messageDAO.selectAll();
	}

	public MessageVO getById(String id) throws Exception {
		if (StringUtils.isEmpty(id) || Integer.parseInt(id)<1)
			return null;
		try {
			Map paramMap = new HashMap();
			paramMap.put("id", new Integer(id));
			Object obj = messageDAO.selectById(paramMap);
			return obj==null?null:(MessageVO)obj;
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			throw new BaseException(MessageServiceImpl.class.getName()+" >> public MessageVO get(String id) error occur:",e);
		}
	}
	public List<MessageVO> getByMap(Map paramMap) throws BaseException {
		try{
			return messageDAO.selectByMap(paramMap);
		}catch(Exception e){
			logger.error(e.getMessage(), e);
			throw new BaseException(MessageServiceImpl.class.getName()+" >> public Collection getByMap(Map map) error occur:",e);
		}
	}

	public int getCountByMap(Map paramMap) throws BaseException {
		try {
			return messageDAO.selectCountByMap(paramMap);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			throw new BaseException(MessageServiceImpl.class.getName()
					+ " >> public Collection getCountByMap(Map map) error occur:", e);
		}
	}

	public List get(Map paramMap, Paginator paginator) throws Exception {
		if (MapCollectionUtils.isEmpty(paramMap)) {
			return null;
		}
		try {
			Map map = new HashMap();
			map.put("paramMap", paramMap);
			return messageDAO.selectForPage(map, paginator);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			throw new BaseException(MessageServiceImpl.class.getName()+" >> public Page (Map paramMap, Paginator paginator) error occur:",e);
		}
	}

	public MessageVO save(MessageVO voObject) throws Exception {
		if (voObject == null)
			return null;
		try {
			Object id = null;
			id = voObject.getId();
			Map paramMap = MapCollectionUtils.removeEmptyEntry(PropertyUtils.describe(voObject));
			if (id != null) {
				messageDAO.updateByMap(paramMap);
				return voObject;
			} else {
				return (MessageVO)messageDAO.insertByVo(voObject);
			}
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			throw new BaseException(MessageServiceImpl.class.getName()+" >> public MessageVO save(MessageVO voObject) error occur:",e);
		}
	}

	public Collection save(Collection voList) throws Exception {
		if (CollectionUtils.isEmpty(voList))
			return null;
		try {
			Iterator it = voList.iterator();
			while (it.hasNext()) {
				MessageVO data = (MessageVO) it.next();
				data = save(data);
			}
			return voList;
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			throw new BaseException(MessageServiceImpl.class.getName()+" >> public Collection save(Collection voList) error occur:",e);
		}
	}

	public boolean remove(List ids) throws Exception {
		if (CollectionUtils.isEmpty(ids))
			return false;
		try{
			messageDAO.deleteByIds(ids);
			return true;
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			throw new BaseException(MessageServiceImpl.class.getName()+" >> public boolean remove(List ids) error occur:",e);
		}
	}

	public boolean removeByMap(Map paramMap) throws Exception {
		if (CollectionUtils.isEmpty(paramMap))
			return false;
		try {
			messageDAO.deleteByMap(paramMap);
			return true;
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			throw new BaseException(MessageServiceImpl.class.getName()+" >> public boolean removeByMap(Map paramMap) error occur:",e);
		}
	}
	
	public void insertSendMsg(List<MessageVO> msgs, Map paramMap) throws Exception {
		if (msgs == null || msgs.size() == 0 )
			return;
		try {
			messageDAO.batchInsert(msgs);
			if(paramMap.size() > 0){
				//customerAccountDAO.updateByMap(paramMap);
				customerDAO.updateByMap(paramMap);
			}
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			throw new BaseException(MessageServiceImpl.class.getName()+" >> public MessageVO save(MessageVO voObject) error occur:",e);
		}
	}
	public void iphonePush(String content,String deviceToken) throws Exception{
		// 注册deviceToken
		PushNotificationManager pushManager = PushNotificationManager.getInstance();
		try {
			// 从客户端获取的deviceToken
			logger.info("=====begin push===");
			String pushContent = content;
			if (content.length() > 71) {
				pushContent = content.substring(0, 71);
			}
			content = content.replace(pushContent, "");
			PayLoad payLoad = new PayLoad();
			payLoad.addAlert(pushContent);
			payLoad.addBadge(4);
			payLoad.addSound("default");

			pushManager.addDevice("iPhone", deviceToken);
			// 连接APNS
			String host = ConfigHelper.fastGetConfig("iphnoepush", "host", "gateway.sandbox.push.apple.com");
			String port = ConfigHelper.fastGetConfig("iphnoepush", "port", "2195");
			String certificatePath = ConfigHelper.fastGetConfig("iphnoepush", "certificatePath", "/data/tomcat6/younion/iphone/iPush.p12");
			String certificatePassword = ConfigHelper.fastGetConfig("iphnoepush", "certificatePassword", "unkonow");
			pushManager.initializeConnection(host, Integer.parseInt(port), certificatePath,
					certificatePassword,
					SSLConnectionHelper.KEYSTORE_TYPE_PKCS12);
			// 发送推送
			Device client = pushManager.getDevice("iPhone");
			pushManager.sendNotification(client, payLoad);
			if(content.length()>0){
				// 停止连接APNS
				pushManager.stopConnection();
				// 删除deviceToken
				pushManager.removeDevice("iPhone");
				iphonePush(content,deviceToken);
			}
			logger.info("=====end push======");
		} catch (Exception ex) {
			logger.info(ex);
			throw new Exception(ex);
		}finally{
			logger.info("====stopConnection====");
			// 停止连接APNS
			try{
				pushManager.stopConnection();
				// 删除deviceToken
				pushManager.removeDevice("iPhone");
			}catch(Exception e){
				logger.info("the finally exception"+e);
			}
		}
	}
	/**
	 * @param service
	 */
	public void setMessageDAO(MessageDAO messageDAO) {
		this.messageDAO = messageDAO;
	}

	public CustomerDAO getCustomerDAO() {
		return customerDAO;
	}

	public void setCustomerDAO(CustomerDAO customerDAO) {
		this.customerDAO = customerDAO;
	}

	public MessageDAO getMessageDAO() {
		return messageDAO;
	}

	/*public void setCustomerAccountDAO(CustomerAccountDAO customerAccountDAO) {
		this.customerAccountDAO = customerAccountDAO;
	}*/

	
	
}